package Entity;

import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CsvFileUtil {
    public static final String BASE_DIR = "D:\\作业\\软件构造\\";
    private static final Pattern EXERCISE_FILE_PATTERN = Pattern.compile(
            "^Exercise_([A-Za-z]+)_([0-9]{8})_([0-9]{1,3})\\.csv$"
    );

    // 读取习题文件（无修改）
    public static List<Exercise> readExercises(String filePath) throws IOException {
        List<Exercise> exerciseList = new ArrayList<>();
        CsvReader csvReader = new CsvReader(filePath, ',', StandardCharsets.UTF_8);
        csvReader.readHeaders();

        String[] headers = csvReader.getHeaders();
        if (!"ExerciseId".equals(headers[0]) || !"Num1".equals(headers[1]) || !"Operator".equals(headers[2])
                || !"Num2".equals(headers[3]) || !"CorrectAnswer".equals(headers[4])) {
            throw new IOException("习题文件格式错误，表头不符合要求：" + String.join(",", headers));
        }

        while (csvReader.readRecord()) {
            try {
                String exerciseId = csvReader.get("ExerciseId").trim();
                int num1 = Integer.parseInt(csvReader.get("Num1").trim());
                char operator = csvReader.get("Operator").trim().charAt(0);
                int num2 = Integer.parseInt(csvReader.get("Num2").trim());
                int correctAnswer = Integer.parseInt(csvReader.get("CorrectAnswer").trim());

                Exercise exercise = new Exercise(
                        exerciseId.split("_")[0],
                        exerciseId.split("_")[1],
                        exerciseId.split("_")[2],
                        Integer.parseInt(exerciseId.split("_")[3]),
                        num1, operator, num2, correctAnswer
                );
                exerciseList.add(exercise);
            } catch (Exception e) {
                throw new IOException("读取习题文件失败，第" + (csvReader.getCurrentRecord() + 1) + "行数据异常：" + csvReader.getRawRecord(), e);
            }
        }
        csvReader.close();
        return exerciseList;
    }

    // 写入习题文件（无修改）
    public static void writeExerciseToCsv(List<Exercise> exerciseList, String filePath) throws IOException {
        CsvWriter csvWriter = new CsvWriter(filePath, ',', StandardCharsets.UTF_8);
        csvWriter.writeRecord(new String[]{"ExerciseId", "Num1", "Operator", "Num2", "CorrectAnswer"});
        for (Exercise exercise : exerciseList) {
            csvWriter.write(exercise.getExerciseId());
            csvWriter.write(String.valueOf(exercise.getNum1()));
            csvWriter.write(String.valueOf(exercise.getOperator()));
            csvWriter.write(String.valueOf(exercise.getNum2()));
            csvWriter.write(String.valueOf(exercise.getCorrectAnswer()));
            csvWriter.endRecord();
        }
        csvWriter.close();
        System.out.println("习题文件生成成功：" + filePath);
    }

    // 写入练习记录（适配 Integer 类型，支持 null）
    public static void writePracticeRecords(List<PracticeRecord> records, String filePath) throws IOException {
        CsvWriter csvWriter = new CsvWriter(filePath, ',', StandardCharsets.UTF_8);
        csvWriter.writeRecord(new String[]{"ExerciseId", "UserAnswer", "IsCompleted", "AnswerTime"});
        for (PracticeRecord record : records) {
            // 修复：Integer 可与 null 比较，调用 toString() 前先判断
            String userAnswerStr = record.getUserAnswer() == null ? "" : record.getUserAnswer().toString();
            csvWriter.write(record.getExerciseId());
            csvWriter.write(userAnswerStr);
            csvWriter.write(String.valueOf(record.isCompleted()));
            csvWriter.write(record.getAnswerTime());
            csvWriter.endRecord();
        }
        csvWriter.close();
    }

    // 读取练习记录（适配 Integer 类型，空字符串转为 null）
    public static List<PracticeRecord> readPracticeRecords(String filePath) throws IOException {
        List<PracticeRecord> records = new ArrayList<>();
        CsvReader csvReader = new CsvReader(filePath, ',', StandardCharsets.UTF_8);
        csvReader.readHeaders();
        while (csvReader.readRecord()) {
            String exerciseId = csvReader.get("ExerciseId").trim();
            String userAnswerStr = csvReader.get("UserAnswer").trim();
            // 修复：空字符串转为 null（适配 Integer 类型）
            Integer userAnswer = userAnswerStr.isEmpty() ? null : Integer.parseInt(userAnswerStr);
            boolean isCompleted = Boolean.parseBoolean(csvReader.get("IsCompleted"));
            String answerTime = csvReader.get("AnswerTime");
            records.add(new PracticeRecord(exerciseId, userAnswer, isCompleted, answerTime));
        }
        csvReader.close();
        return records;
    }

    // 获取下一个序号（无修改）
    public static String getNextSeq(String date, String type) {
        File dir = new File(BASE_DIR);
        if (!dir.exists() || !dir.isDirectory()) {
            throw new IllegalArgumentException("存储目录不存在或不是文件夹：" + BASE_DIR);
        }

        File[] files = dir.listFiles(file -> {
            if (!file.isFile() || !file.getName().endsWith(".csv")) {
                return false;
            }
            String fileName = file.getName();
            Matcher matcher = EXERCISE_FILE_PATTERN.matcher(fileName);
            if (!matcher.matches()) {
                return false;
            }
            String fileType = matcher.group(1);
            String fileDate = matcher.group(2);
            return fileType.equalsIgnoreCase(type) && fileDate.equals(date);
        });

        int maxSeq = 0;
        if (files != null && files.length > 0) {
            for (File file : files) {
                Matcher matcher = EXERCISE_FILE_PATTERN.matcher(file.getName());
                if (matcher.matches()) {
                    String seqStr = matcher.group(3);
                    try {
                        int seq = Integer.parseInt(seqStr);
                        maxSeq = Math.max(maxSeq, seq);
                    } catch (NumberFormatException e) {
                        System.err.println("警告：文件名序号非法，已忽略：" + file.getName());
                    }
                }
            }
        }

        return String.format("%03d", maxSeq + 1);
    }
}